package com.ggh.jinjilive.ui.mall.goods;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ActivityAddGoodsBinding;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener1;
import com.ggh.jinjilive.mobile.mall.MallPointsClass;
import com.ggh.jinjilive.mobile.mall.goods.GoodsSpecificationMobile;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.mall.goods.adapter.AddImageGoodsAdapter;
import com.ggh.jinjilive.ui.mall.goods.adapter.AddSpecificationAdapter;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.GlideEngine;
import com.ggh.jinjilive.views.GridItemDecoration;
import com.ggh.jinjilive.views.adapter.ColumnAdapter;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 添加商品
 */

@Route(path = ARouterUtils.AddGoodsActivity)
public class AddGoodsActivity extends BaseActivity<ActivityAddGoodsBinding> implements View.OnClickListener {
    //VM
    private GoodsViewModel goodsViewModel;
    //适配器
    private AddImageGoodsAdapter addImageGoodsAdapter;
    //商品主图
    private String advocatePicture = "";
    //选择图片
    public List<String> photoList = new ArrayList<>();
    //分类的适配器
    private ColumnAdapter columnAdapter;
    //添加规格
    private List<GoodsSpecificationMobile> goodsSpecificationMobileList = new ArrayList<>();
    //规格适配器
    private AddSpecificationAdapter addSpecificationAdapter;
    //选中的分类
    private MallPointsClass mallPointsClass;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).keyboardEnable(true).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        goodsViewModel = new ViewModelProvider(this,viewModelFactory).get(GoodsViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_add_goods;

    }


    @Override
    public void initView() {
        super.initView();
        setWhiteActionBarStyle("添加商品",true,true);
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);
        //适配器
        addImageGoodsAdapter = new AddImageGoodsAdapter();
        addImageGoodsAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position == 999999){//添加图片
                    EasyPhotos.createAlbum(AddGoodsActivity.this, true,false, GlideEngine.getInstance()).setFileProviderAuthority("com.ggh.jinjilive.fileprovider").start(new SelectCallback() {
                        @Override
                        public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                            if(photos.size() > 0){
                                goodsViewModel.uploadimages(photos.get(0).path, new AddOnClickListener1() {
                                    @Override
                                    public void onSkipClicked(Object mObject) {
                                        String uploadPicture = (String) mObject;
                                        if(null != uploadPicture){
                                            if(photoList.size() >= 2){
                                                photoList.add(photoList.size() -1,uploadPicture);
                                            }else {
                                                photoList.add(0,uploadPicture);
                                            }
                                            if(photoList.size() == 4){
                                                photoList.remove(photoList.size()-1);
                                            }
                                            addImageGoodsAdapter.setAdd(photoList);
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                }else {//修改
                    EasyPhotos.createAlbum(AddGoodsActivity.this, true,false, GlideEngine.getInstance()).setFileProviderAuthority("com.ggh.jinjilive.fileprovider").start(new SelectCallback() {
                        @Override
                        public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                            if(photos.size() > 0){
                                goodsViewModel.uploadimages(photos.get(0).path, new AddOnClickListener1() {
                                    @Override
                                    public void onSkipClicked(Object mObject) {
                                        String uploadPicture = (String) mObject;
                                        if(null != uploadPicture){
                                            photoList.set(position,uploadPicture);
                                            addImageGoodsAdapter.setAdd(photoList);
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                }
            }
        });
        binding.addGoodsRv.setLayoutManager(new GridLayoutManager(mContext,3));
        binding.addGoodsRv.addItemDecoration(new GridItemDecoration(3, ConvertUtils.dp2px(10),true));
        binding.addGoodsRv.setAdapter(addImageGoodsAdapter);
        //选择图片
        photoList.clear();
        photoList.add(null);
        addImageGoodsAdapter.setAdd(photoList);

    }

    @Override
    public void initData() {
        super.initData();
        //获取商品分类
        goodsViewModel.productType();
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //添加商品主图
        binding.imgAddGoodsPicture.setOnClickListener(this);
        //确认添加
        binding.affirmAdd.setOnClickListener(this);
        //上传
        binding.tvConfirm.setOnClickListener(this);


        //规格适配器
        addSpecificationAdapter = new AddSpecificationAdapter();
        addSpecificationAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position != 999999){
                    goodsSpecificationMobileList.remove(position);
                    addSpecificationAdapter.notifyDataSetChanged();
                }
            }
        });
        //下拉框
        binding.benefitType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                mallPointsClass = (MallPointsClass) columnAdapter.getItem(position);
                LogUtils.d("下拉框" + new Gson().toJson(mallPointsClass));
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        binding.rvSpecification.setLayoutManager(new LinearLayoutManager(mContext));
        binding.rvSpecification.setAdapter(addSpecificationAdapter);

        //获取商品分类
        goodsViewModel.listMutableLiveData.observe(this, new Observer<List<MallPointsClass>>() {
            @Override
            public void onChanged(List<MallPointsClass> mallPointsClasses) {
                if(mallPointsClasses.size() > 0){
                    //适配器
                    columnAdapter = new ColumnAdapter(mContext, mallPointsClasses);
                    binding.benefitType.setAdapter(columnAdapter);
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_add_goods_picture://添加商品主图
                EasyPhotos.createAlbum(this, true,false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                        .setFileProviderAuthority("com.ggh.jinjilive.fileprovider")//参数说明：见下方`FileProvider的配置`
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                goodsViewModel.uploadimages(photos.get(0).path, new AddOnClickListener1() {
                                    @Override
                                    public void onSkipClicked(Object mObject) {
                                        advocatePicture = (String) mObject;
                                        if(null != advocatePicture){
                                            Glide.with(binding.imgAddGoodsPicture).load(advocatePicture).into(binding.imgAddGoodsPicture);
                                        }

                                    }
                                });
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                break;
            case R.id.affirm_add://确认添加
                //规格
                String etSpecification = binding.etSpecification.getText().toString();
                if(TextUtils.isEmpty(etSpecification)){
                    ToastUtils.make().show("请填写规格名称");
                    return;
                }
                //库存
                String etInventory = binding.etInventory.getText().toString();
                if(TextUtils.isEmpty(etInventory)){
                    ToastUtils.make().show("请填写库存");
                    return;
                }
                //价格
                String etPrice = binding.etPrice.getText().toString();
                if(TextUtils.isEmpty(etPrice)){
                    ToastUtils.make().show("请填写价格");
                    return;
                }
                GoodsSpecificationMobile goodsSpecificationMobile = new GoodsSpecificationMobile();
                //规格
                goodsSpecificationMobile.setName(etSpecification);
                //库存
                goodsSpecificationMobile.setStock(Integer.parseInt(etInventory));
                //价格
                goodsSpecificationMobile.setFee(Double.parseDouble(etPrice));
                //添加数据
                goodsSpecificationMobileList.add(goodsSpecificationMobile);
                addSpecificationAdapter.setAdd(goodsSpecificationMobileList);
                break;
            case R.id.tv_confirm://上传
                Map<String, Object> map = new HashMap<>();
                //主图
                if(TextUtils.isEmpty(advocatePicture)){
                    ToastUtils.make().show("请添加商品主图");
                    return;
                }else {
                    map.put("img",advocatePicture);
                }

                //添加商品标题
                String goodsTitle = binding.rtGoodsTitle.getText().toString();
                if(TextUtils.isEmpty(goodsTitle)){
                    ToastUtils.make().show("请填写商品标题");
                    return;
                }else {
                    map.put("name",goodsTitle);
                }

                if(photoList.size() != 3){
                    ToastUtils.make().show("请至少添加三张商品图片");
                    return;
                }else {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i =0; i< photoList.size(); i++){
                        stringBuilder.append(photoList.get(i));

                        if (i != photoList.size()-1){
                            stringBuilder.append(",");
                        }
                    }
                    map.put("imglist",stringBuilder.toString());
                }
                //请填写卖点描述
                String goodsDescribe = binding.etGoodsDescribe.getText().toString();
                if(TextUtils.isEmpty(goodsDescribe)){
                    ToastUtils.make().show("请填写卖点描述");
                    return;
                }else {
                    map.put("describes",goodsDescribe);
                }
                map.put("types",mallPointsClass.getId());
                //规格
                if(goodsSpecificationMobileList.size() ==  0){
                    ToastUtils.make().show("请至少添加一种规格");
                    return;
                }else {
                    map.put("price",goodsSpecificationMobileList.get(0).getFee());
                    map.put("fee",goodsSpecificationMobileList.get(0).getFee());
                    map.put("spec", goodsSpecificationMobileList);
                }
                //上架商品
                goodsViewModel.editProduct(map);
                break;
        }
    }

}
